package com.skt.config;

import com.skt.domain.ENUM.AccountStatus;
import com.skt.domain.ENUM.UserRole;
import com.skt.domain.PO.User;
import com.skt.security.LoginUser;
import com.skt.service.UserService;
import com.skt.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {

        log.info("🔍 JwtAuthenticationFilter 被调用！URL: {}", request.getRequestURI());
        log.info("🔍 Authorization Header: {}", request.getHeader("Authorization"));

        String token = resolveToken(request);
        if (token != null && jwtUtil.validateToken(token)) {
            String username = jwtUtil.getUsernameFromToken(token);

            User user = userService.getUserByUsername(username);
            if (user == null) {
                log.warn("❌ 无效用户: {}", username);
                filterChain.doFilter(request, response);
                return;
            }

            // >>>>>>>>>> 修复开始 <<<<<<<<<<
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            UserRole userRole = user.getRole();
            if (userRole != null) {
                String role = userRole == UserRole.ADMIN ? "ROLE_ADMIN" : "ROLE_USER";
                authorities.add(new SimpleGrantedAuthority(role));
            }

            AccountStatus accountStatus = user.getAccountStatus();
            boolean enabled = accountStatus != null && accountStatus == AccountStatus.ENABLED;
            // >>>>>>>>>> 修复结束 <<<<<<<<<<

            LoginUser loginUser = new LoginUser(
                    user.getId(),
                    user.getUsername(),
                    authorities,
                    enabled
            );

            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

            SecurityContextHolder.getContext().setAuthentication(authentication);
        }

        filterChain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}